package com.zhang.es;

import com.google.gson.Gson;
import com.zhang.model.User;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

import java.io.EOFException;
import java.net.InetAddress;
import java.util.Map;

/**
 * @program: elasitcsearch
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-03-17
 **/
public class Fuxiday4 {
    private TransportClient client;
    @Before
    public void createClient() throws Exception{
        Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build();
        client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.117.131"),9301))
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.117.130"),9302));

    }
    @Test
    public void addIndex(){
        client.admin().indices().prepareCreate("java3").get();
        client.close();
    }
    @Test
    public void putMapping()throws  Exception{
        XContentBuilder builder = XContentFactory.jsonBuilder();

        builder
            .startObject()
                .startObject("user")
                        .startObject("properties")
                            .startObject("id")
                                .field("type","long")
                                .field("store",true)
                            .endObject()
                            .startObject("userName")
                                .field("type","text")
                                .field("index",true)
                                .field("store",true)
                                .field("analyzer","ik_smart")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject();
        client.admin().indices().preparePutMapping("java3").setType("user").setSource(builder).get();
        client.close();
    }

    @Test
    public void addDoc(){
        for (int i = 0; i < 30; i++) {
           User user = new User(i,"南京的冬天，好像比去年来得晚些，空气里弥漫着冬天特有的烤红薯的味道，人们还是像往常一样重复着单一的生活。“呼呼呼……”少年模样的人在街上穿梭着，双脚踩在地上发出沓沓声，即使是深冬早晨冰冷的路面，也阻挡不了他的步伐，好像没有知觉似的，往前跑着。");
            Gson gson = new Gson();
            String s = gson.toJson(user);
            client.prepareIndex()
                  .setIndex("java3")
                  .setType("user")
                  .setSource(s)
                  .setId(i+"")
                  .get();
        }
            client.close();
    }
    @Test
    public void delDoc(){
        client.prepareDelete()
              .setIndex("java3")
              .setType("user")
              .setId("0")
              .get();
        client.close();
    }
    @Test
    public void searchDoc(){
        QueryBuilder builder = QueryBuilders.boolQuery().must(QueryBuilders.queryStringQuery("南京").defaultField("userName"));
        SearchResponse searchResponse = client.prepareSearch().setIndices("java3").setTypes("user").setQuery(builder).setFrom(0).setSize(10).get();
        SearchHits hits = searchResponse.getHits();
        System.out.println(hits.getTotalHits()+"查询的总条数为");
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit searchHitFields : hits1) {
            Map<String, Object> source = searchHitFields.getSource();
            System.out.println("id编号为+"+source.get("id"));
            System.out.println("userName为+"+source.get("userName"));
        }
        client.close();
    }
    @Test
    public void searchHigh(){
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("userName").preTags("<span style="+"color=red"+">").postTags("<span>");
        QueryBuilder builder = QueryBuilders.boolQuery().must(QueryBuilders.queryStringQuery("南京").defaultField("userName"));
        SearchResponse searchResponse = client.prepareSearch().setIndices("java3").setTypes("user").setQuery(builder).highlighter(highlightBuilder).get();
        SearchHits hits = searchResponse.getHits();
        System.out.println(hits.getTotalHits()+"总条数");
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit searchHitFields : hits1) {
            System.out.println(searchHitFields.getSourceAsString());

            Map<String, HighlightField> highlightFields = searchHitFields.getHighlightFields();
            HighlightField userName = highlightFields.get("userName");
            Text[] fragments = userName.fragments();
            for (Text fragment : fragments) {
                System.out.println(fragment);
            }

        }

    }

}
